<template>
  <div id="student">

    <!--  回到顶部  -->
    <el-backtop target="#student" :visibility-height="10"></el-backtop>

    <div class="table-header">
      <h1>学生管理</h1>
      <el-button type="warning" icon="el-icon-circle-plus" @click="handleAddStu">添加学生</el-button>
    </div>

    <!--  表格部分  -->
    <el-card class="box-card">
      <template>
        <el-table v-loading="loading" :data="students" stripe style="width: 100%"
                  element-loading-text="拼命加载中"
                  element-loading-spinner="el-icon-loading">
          <el-table-column
              prop="id"
              label="学号">
          </el-table-column>
          <el-table-column
              prop="userName"
              label="姓名">
          </el-table-column>
          <el-table-column
              prop="phone"
              label="手机">
          </el-table-column>
          <el-table-column
              label="性别">
            <template slot-scope="scope">
              {{ scope.row.sex == '0' ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" min-width="180px" resizable>
          </el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status == 0" size="small" type="success">{{
                  scope.row.status == '0' ? '正常' : '禁用'
                }}
              </el-tag>
              <el-tag v-else size="small" type="danger">{{ scope.row.status == '0' ? '正常' : '禁用' }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button type="primary" size="mini" @click="handleModify(scope.row.id)">修改</el-button>
              <el-button @click="handleDel(scope.row.id)" type="danger" size="mini">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
      </template>
      <!--  表格结束    -->
    </el-card>

    <!--  分页  -->
    <el-pagination
        background layout="total,prev, pager, next,sizes"
        :total="total"
        :page-sizes="[8, 12, 16]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :page-size="pageSize">
    </el-pagination>

    <!--  Dialog，用于添加，修改学生  -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" :close-on-click-modal="false">

      <el-form :inline="true" ref="stuForm" :model="student" :rules="rules">

        <el-row>
          <el-col :span="11">
            <el-form-item label="学号" prop="id">
              <el-input :disabled="!isAdd" v-model="student.id" placeholder="学号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="姓名" prop="userName">
              <el-input v-model="student.userName" placeholder="姓名"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="11">
            <el-form-item label="手机" prop="phone">
              <el-input v-model="student.phone" placeholder="手机"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="性别" v-model="student.sex">
              <el-select v-model="student.sex" placeholder="性别">
                <el-option label="男" value="0"></el-option>
                <el-option label="女" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="student.email" placeholder="邮箱"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="11">
            <el-form-item label="状态" v-model="student.status">
              <el-select v-model="student.status" placeholder="状态">
                <el-option label="正常" value="0"></el-option>
                <el-option label="禁用" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row type="flex" class="row-bg" justify="center">
          <el-col :span="12">
            <el-form-item>
              <el-button type="primary" @click="onSubmit">{{ isAdd ? "添加" : "修改" }}</el-button>
              <el-button @click="handleClose">取消</el-button>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

    </el-dialog>
  </div>
</template>

<script>
import {pageStudents, delStudent, getStudentById, addStudent, updateStudent} from "@/api/student";

export default {
  name: "Student",
  data() {
    const checkId = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('学号不能为空'));
      } else if (value.toString().length < 7 || value.toString().length > 10) {
        callback(new Error('长度在 7 到 10 个字符'));
      }
      setTimeout(() => {
        if (!parseInt(value)) {
          callback(new Error('请输入数字值'));
        } else {
          callback();
        }
      }, 500);
    };
    const checkPhone = (rule, value, callback) => {
      const regExp = new RegExp("^1(3\\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\\d|9[0-35-9])\\d{8}$");
      if (!value) {
        callback(new Error('手机号不能为空'));
      } else if (!regExp.test(value)) {
        callback(new Error('请输入正确格式的手机号'));
      } else {
        callback();
      }
    };
    const checkEmail = (rule, value, callback) => {
      const regExp = new RegExp("[a-zA-Z0-9]+([-_.][A-Za-zd]+)*@([a-zA-Z0-9]+[-.])+[A-Za-zd]{2,5}$");
      if (!value) {
        callback(new Error('邮箱不能为空'));
      } else if (!regExp.test(value)) {
        callback(new Error('请输入正确格式的邮箱地址'));
      } else {
        callback();
      }
    };
    return {
      loading: true,
      student: {
        status: '0',
        sex: '0'
      },
      students: [],
      total: 0,
      pageNum: 1,
      pageSize: 8,
      dialogFormVisible: false,
      dialogTitle: "",
      isAdd: true,
      rules: {
        id: [
          {validator: checkId, trigger: 'blur'},
        ],
        userName: [
          {required: true, message: '请输入学生的姓名', trigger: 'blur'},
        ],
        phone: [
          {validator: checkPhone, trigger: 'blur'},
        ],
        email: [
          {validator: checkEmail, trigger: 'blur'},
        ]
      }
    }
  },
  mounted() {
    this.getUser()
  },
  methods: {
    getUser() {
      this.loading = true
      pageStudents(this.pageNum, this.pageSize).then(res => {
        this.students = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getUser()
    },
    handleCurrentChange(val) {
      this.pageNum = val
      this.getUser()
    },
    handleDel(id) {
      this.$confirm('此操作将永久删除该学生, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delStudent(id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.getUser()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleModify(id) {

      getStudentById(id).then(res => {
        this.student = res
      })

      this.dialogTitle = "修改用户"
      this.dialogFormVisible = true
      this.isAdd = false
    },
    handleAddStu() {
      this.dialogTitle = "添加用户"
      this.dialogFormVisible = true
      this.isAdd = true
    },
    handleClose() {
      this.dialogFormVisible = false
      this.$message(`已经取消${this.isAdd ? '添加' : '修改'}学生`);
      this.student = {
        status: '0',
        sex: '0'
      }
    },
    onSubmit() {
      this.$refs.stuForm.validate((valid) => {
        if (valid) {
          if (this.isAdd) {
            //添加用户的操作
            addStudent(this.student).then(res => {
              if (res.code == 200) {
                this.$message.success(res.msg);
              } else {
                this.$message.error(res.msg);
              }
              this.dialogFormVisible = false
              this.getUser()
            })
          } else {
            //修改用户
            updateStudent(this.student).then(res => {
              if (res.code == 200) {
                this.$message.success(res.msg);
              } else {
                this.$message.error(res.msg);
              }
              this.dialogFormVisible = false
              this.getUser()
            })
          }
        } else {
          this.$message.error('请填写或者修正内容！！！');
          return false;
        }
      });
    }
  }
}
</script>

<style scoped lang="less">

#student {

  width: 100%;
  height: 100%;
  /* 这里给app一个滚动效果 */
  overflow-y: scroll;
}

.table-header {
  height: 40px;
  line-height: 40px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;

  h1 {
    font-size: 20px;
    margin-left: 10px;
  }

  .el-button {
    margin-right: 10px;
  }
}

.el-pagination {
  margin-top: 12px;
}
</style>
